package com.birdy.jwt.service.impl;

import com.birdy.jwt.config.EncryptConfigProperties;
import com.birdy.jwt.service.IEncryptService;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class EncryptServiceImpl implements IEncryptService {
    @Autowired
    private EncryptConfigProperties encryptConfigProperties; // 属性配置
    private static MessageDigest MD5_DIGEST; // MD5加密处理
    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); // 加密器
    private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); // 解密器
    static {    // 初始化操作
        try {
            MD5_DIGEST = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    @Override
    public String getEncryptPassword(String password) {
        String saltPassword = "{" + this.encryptConfigProperties.getSalt() + "}" + password;
        for (int x = 0 ; x < this.encryptConfigProperties.getRepeat(); x ++) {
            saltPassword = BASE64_ENCODER.encodeToString(MD5_DIGEST.digest(saltPassword.getBytes()));
        }
        return saltPassword;
    }
    public String encryptBase64Password(String password) {
        String saltPassword = "{" + this.encryptConfigProperties.getSalt() + "}" + password;
        for (int x = 0 ; x < this.encryptConfigProperties.getRepeat(); x ++) {
            saltPassword = BASE64_ENCODER.encodeToString(saltPassword.getBytes(StandardCharsets.UTF_8));
        }
        return saltPassword;
    }
    public String decryptBase64Password(String base64Password) {
        byte[] data = base64Password.getBytes(StandardCharsets.UTF_8);
        for (int x = 0 ; x < this.encryptConfigProperties.getRepeat(); x ++) {
            data = BASE64_DECODER.decode(data);
        }
        String password = new String(data);
        return password.substring(("{" + this.encryptConfigProperties.getSalt() + "}").length());
    }
}
